/* +----------------------------------------------------------------------
| 麦沃德科技赋能开发者，助力中小企业发展 
+----------------------------------------------------------------------
| Copyright (c) 2017～2024  www.wdadmin.cn    All rights reserved.
+----------------------------------------------------------------------
| 沃德代驾系统并不是自由软件，不加密，并不代表开源，未经许可不可自由转售和商用
+----------------------------------------------------------------------
| Author: MY WORLD Team <bd@maiwd.cn>   www.wdadmin.cn
+---------------------------------------------------------------------- */
import $request from "./request.js"
import apiMap from "./api/index.js";
import permission from "@/common/permission.js";
import store from '@/store'

export default {
	// 接口请求
	request(apiKey, params, config) {
		const apiConfig = this.getApiConfig(apiKey)
		return $request.request(apiConfig, params, config)
	},

	// 解析API配置
	getApiConfig(apiKey) {
		try {
			return apiKey.split('.').reduce((acc, key) => {
				if (!acc[key]) throw new Error('无效的API路径');
				return acc[key];
			}, apiMap);
		} catch {
			return {};
		}
	},

	// 验证是否登录
	verifyLogin() {
		if (!uni.getStorageSync("token")) {
			uni.navigateTo({
				url: "/pages/public/login/index",
				animationType: "fade-in"
			})
			return false
		} else return true
	},

	// 上传文件-单文件
	uploadFile(file) {
		return new Promise((resolve, reject) => {
			// 判断有无网络
			uni.getNetworkType({
				success: (res) => {
					if (res.networkType === "none") {
						uni.showToast({
							icon: "none",
							title: "请先连接网络后操作"
						})
						uni.hideLoading()
					} else {
						uni.uploadFile({
							url: getApp().globalData.adminPath + '/api/wddj/common/upload',
							filePath: file,
							name: 'file',
							header: {
								token: uni.getStorageSync("token"),
							},
							success: (res) => {
								resolve(JSON.parse(res.data))
							},
							fail: (err) => {
								reject(err)
							}
						})
					}
				}
			})
		})
	},

	/* 上传文件-多文件
		 files:  待上传文件
		 oldFiles: 已上传文件
	*/
	uploadFileMultiple(files, oldFiles) {
		return new Promise((resolve, reject) => {
			var uploadList = new Array(files.length)
			var completeNum = 0
			for (var i in files) {
				const index = i
				if (oldFiles && oldFiles.includes(files[i])) {
					uploadList[index] = files[i]
					if (++completeNum == files.length) {
						resolve(uploadList)
					}
				} else {
					this.uploadFile(files[i]).then((res) => {
						if (res.code == 1) {
							uploadList[index] = res.data.url
							if (++completeNum == files.length) {
								resolve(uploadList)
							}
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							})
							reject(res.msg)
						}
					}).catch(err => {
						reject(err)
					})
				}
			}
		})
	},

	/* 导航菜单跳转及功能
		e.mode: 1.跳转内部页面，2.关闭当前页面跳转，3.关闭所有页面跳转，4.跳转外部链接，5.跳转微信小程序，6.拨打电话，7.地图导航，8.复制文本
		e.path: 跳转页面时使用的地址
		e.appId: 跳转小程序时使用的小程序id或原始id
		e.phone: 拨打电话时使用的电话号码
		e.address: 地图导航时使用的地址
		e.content: 复制文本时使用的文本
	*/
	toPage(e) {
		if (e.mode == 1 || e.mode == 2 || e.mode == 3) {
			// 底部导航
			let tabbarList = [
				'/pages/driver/index/index',
				'/pages/driver/order/index',
				'/pages/driver/message/index',
				'/pages/driver/mine/index',
			]
			// 实名认证状态
			const userInfo = uni.getStorageSync("userInfo")
			// 判断是否可以跳转
			if (e.isToken && !uni.getStorageSync("token")) { // 是否登录
				uni.navigateTo({
					url: "/pages/public/login/index",
					animationType: "fade-in"
				})
			} else if (e.permission && userInfo.certification_examine_status != 2) { // 判断是否实名认证
				uni.showModal({
					content: '请先进行实名认证后接单， \n 是否前往认证？',
					confirmText: "前往认证",
					confirmColor: store.state.app.themeColor,
					success: (res) => {
						if (res.confirm) {
							uni.navigateTo({
								url: "/pages/driver/mine/authentication/index"
							})
						}
					}
				})
			} else if (tabbarList.indexOf(e.path.split("?")[0]) > -1) { // 链接是否为底部导航
				uni.switchTab({
					url: e.path
				})
			} else {
				if (e.mode == 1) {
					uni.navigateTo({
						url: e.path
					})
				} else if (e.mode == 2) {
					uni.redirectTo({
						url: e.path
					})
				} else if (e.mode == 3) {
					uni.reLaunch({
						url: e.path
					})
				}
			}
		} else {
			if (e.mode == 4) {
				uni.navigateTo({
					url: '/pages/public/webview/webview?path=' + encodeURIComponent(e.path)
				})
			} else if (e.mode == 5) {
				// #ifdef MP-WEIXIN
				uni.navigateToMiniProgram({
					appId: e.appId,
					path: e.path
				})
				// #endif
				// #ifdef APP-PLUS
				plus.share.getServices((s) => {
					var shares = {};
					for (var i = 0; i < s.length; i++) {
						var t = s[i];
						shares[t.id] = t;
					}
					shares['weixin'] ? shares['weixin'].launchMiniProgram({
						id: e.appId,
						path: e.path,
						type: 0, // 小程序版本  0-正式版； 1-测试版； 2-体验版。
					}) : plus.nativeUI.alert('当前环境不支持微信操作!');
				}, (e) => {
					console.error("获取分享服务列表失败：" + e.message);
				});
				// #endif
			} else if (e.mode == 6) {
				// 拨打电话
				if (e.phone) {
					uni.makePhoneCall({
						phoneNumber: e.phone + ""
					});
				} else {
					uni.showToast({
						icon: "none",
						title: "暂无可拨打电话"
					})
				}
			} else if (e.mode == 7) {
				if (e.address && e.address.latitude && e.address.longitude) {
					let location = {
						latitude: Number(e.address.latitude),
						longitude: Number(e.address.longitude),
					}
					if (e.address.name) location.name = e.address.name
					if (e.address.address) location.address = e.address.address
					uni.openLocation(location);
				} else {
					uni.showToast({
						icon: "none",
						title: "暂无相关地址"
					})
				}
			} else if (e.mode == 8) {
				if (e.content) {
					uni.setClipboardData({
						data: e.content,
						success: () => {
							uni.showToast({
								icon: "success",
								title: "复制成功"
							})
						}
					});
				} else {
					uni.showToast({
						icon: "none",
						title: "暂无可复制内容"
					})
				}
			}
		}
	},

	/* 常用规则验证
		 mode: phone-验证手机号，email-验证邮箱，IDcard-身份证号（简单验证），password-密码
		 info: 需要验证的内容
	*/
	validation(mode, info) {
		if (mode == 'phone') {
			var reg = /^1[0-9]{10,10}$/
			if (reg.test(info)) return true;
			else return false;
		} else if (mode == 'email') {
			var reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
			if (reg.test(info)) return true;
			else return false;
		} else if (mode == 'IDcard') {
			var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
			if (reg.test(info)) {
				var birth = (info.length === 18 ? info.slice(6, 14) : info.slice(6, 12));
				var month, day;
				if (birth.length == 8) {
					month = parseInt(birth.slice(4, 6), 10);
					day = parseInt(birth.slice(-2), 10);
				} else if (birth.length == 6) {
					month = parseInt(birth.slice(2, 4), 10);
					day = parseInt(birth.slice(-2), 10);
				} else {
					return false;
				}
				if (month > 12 || month === 0 || day > 31 || day === 0) {
					return false;
				}
				return true;
			} else return false;
		} else if (mode == 'password') {
			if (info.length >= 6) return true;
			else return false;
		}
	},

	/* 时间戳转日期格式 
		 timeStamp: 时间戳
		 format: 日期格式（y-年，m-月，d-日，h-时，i-分，s-秒，M-月(自动补0)，D-日(自动补0)，H-时(自动补0)，I-分(自动补0)，S-秒(自动补0)，W-周）
	*/
	getFormatDate(timeStamp, format = "y-m-d H:I:S") {
		let date = new Date(timeStamp);
		var year = date.getFullYear()
		var month = date.getMonth() + 1
		var day = date.getDate()
		var hour = date.getHours()
		var minute = date.getMinutes()
		var second = date.getSeconds()
		var week = date.getDay()
		if (format.indexOf('y') != -1) {
			format = format.replace(/y/g, year)
		}
		if (format.indexOf('m') != -1) {
			format = format.replace(/m/g, month)
		} else if (format.indexOf('M') != -1) {
			month >= 1 && month <= 9 ? (month = "0" + month) : "";
			format = format.replace(/M/g, month)
		}
		if (format.indexOf('d') != -1) {
			format = format.replace(/d/g, day)
		} else if (format.indexOf('D') != -1) {
			day >= 0 && day <= 9 ? (day = "0" + day) : "";
			format = format.replace(/D/g, day)
		}
		if (format.indexOf('h') != -1) {
			format = format.replace(/h/g, hour)
		} else if (format.indexOf('H') != -1) {
			hour >= 0 && hour <= 9 ? (hour = "0" + hour) : "";
			format = format.replace(/H/g, hour)
		}
		if (format.indexOf('i') != -1) {
			format = format.replace(/i/g, minute)
		} else if (format.indexOf('I') != -1) {
			minute >= 0 && minute <= 9 ? (minute = "0" + minute) : "";
			format = format.replace(/I/g, minute)
		}
		if (format.indexOf('s') != -1) {
			format = format.replace(/s/g, second)
		} else if (format.indexOf('S') != -1) {
			second >= 0 && second <= 9 ? (second = "0" + second) : "";
			format = format.replace(/S/g, second)
		}
		if (format.indexOf('W') != -1) {
			let weekDay = '';
			switch (week) {
				case 0:
					weekDay = '周日';
					break;
				case 1:
					weekDay = '周一';
					break;
				case 2:
					weekDay = '周二';
					break;
				case 3:
					weekDay = '周三';
					break;
				case 4:
					weekDay = '周四';
					break;
				case 5:
					weekDay = '周五';
					break;
				case 6:
					weekDay = '周六';
					break;
			}
			format = format.replace(/W/g, weekDay)
		}
		return format;
	},

	// 日期转时间戳
	getTimeStamp(date) {
		date = date.replace('-', '/');
		date = date.replace('-', '/');
		return new Date(date).getTime()
	},

	/* 获取当前日期
		 format: 日期格式
	*/
	getCurrentDate(format = "y-m-d H:I:S") {
		var date = new Date().getTime()
		var result = this.getFormatDate(date, format)
		return result
	},

	/* 获取几天内的所有日期
		 startDate: 开始日期
		 number: 日期数量
		 format: 日期格式
	*/
	getDateGroup(startDate, number = 4, format = "y-m-d H:I:S") {
		startDate = startDate.replace('-', '/');
		startDate = startDate.replace('-', '/');
		let currentDate = new Date(startDate).getTime();
		let result = [this.getFormatDate(currentDate, format)]
		for (let i = 1; i < parseInt(number); i++) {
			currentDate += 86400000;
			result.push(this.getFormatDate(currentDate, format))
		}
		return result
	},

	/* 获取一定时间前的日期
		 date: 开始时间
		 type: 1-年，2-月，3-日，4-时，5-分，6-秒
		 timeslot: 时间间隙（多少 年/月/日/时/分/秒 之后）
		 format: 日期格式
	*/
	getBeforeDate(date, type, timeslot, format = "y-m-d H:I:S") {
		date = date.replace('-', '/')
		date = date.replace('-', '/')
		let newDate = new Date(date)
		if (type == 1) newDate.setFullYear(newDate.getFullYear() - Number(timeslot))
		else if (type == 2) newDate.setMonth(newDate.getMonth() - Number(timeslot))
		else if (type == 3) newDate.setDate(newDate.getDate() - Number(timeslot))
		else if (type == 4) newDate.setHours(newDate.getHours() - Number(timeslot))
		else if (type == 5) newDate.setMinutes(newDate.getMinutes() - Number(timeslot))
		else if (type == 6) newDate.setSeconds(newDate.getSeconds() - Number(timeslot))
		let result = this.getFormatDate(newDate.getTime(), format)
		return result
	},

	/* 获取一定时间后的日期
		 date: 开始时间
		 type: 1-年，2-月，3-日，4-时，5-分，6-秒
		 timeslot: 时间间隙（多少 年/月/日/时/分/秒 之后）
		 format: 日期格式
	*/
	getAfterDate(date, type, timeslot, format = "y-m-d H:I:S") {
		date = date.replace('-', '/')
		date = date.replace('-', '/')
		let newDate = new Date(date)
		if (type == 1) newDate.setFullYear(newDate.getFullYear() + Number(timeslot))
		else if (type == 2) newDate.setMonth(newDate.getMonth() + Number(timeslot))
		else if (type == 3) newDate.setDate(newDate.getDate() + Number(timeslot))
		else if (type == 4) newDate.setHours(newDate.getHours() + Number(timeslot))
		else if (type == 5) newDate.setMinutes(newDate.getMinutes() + Number(timeslot))
		else if (type == 6) newDate.setSeconds(newDate.getSeconds() + Number(timeslot))
		let result = this.getFormatDate(newDate.getTime(), format)
		return result
	},

	// 获取指定日期的一周开始日期（周一为每周开始，周日为每周结束）
	beginOfWeek(date, format = "y-m-d") {
		date = date.replace('-', '/');
		date = date.replace('-', '/');
		let subDay = 0;
		let weekDay = new Date(date).getDay();
		if (weekDay == 0) {
			subDay = 6;
		} else {
			subDay = weekDay - 1;
		}
		let beginDateTime = new Date(date).getTime() - (86400000 * subDay);
		let result = this.getFormatDate(beginDateTime, format)
		return result
	},

	// 获取指定日期的一周结束日期（周一为每周开始，周日为每周结束）
	endOfWeek(date, format = "y-m-d") {
		date = date.replace('-', '/');
		date = date.replace('-', '/');
		let subDay = 0;
		let weekDay = new Date(date).getDay();
		if (weekDay != 0) subDay = 7 - weekDay;
		let endDateTime = new Date(date).getTime() + (86400000 * subDay);
		let result = this.getFormatDate(endDateTime, format)
		return result
	},

	// 获取指定日期的一个月开始日期
	beginOfMonth(date, format = "y-m-d") {
		date = date.replace('-', '/');
		date = date.replace('-', '/');
		let currenDay = new Date(date);
		currenDay.setDate(1)
		let result = this.getFormatDate(currenDay, format)
		return result
	},

	// 获取指定日期的一个月结束日期
	endOfMonth(date, format = "y-m-d") {
		date = date.replace('-', '/');
		date = date.replace('-', '/');
		let year = new Date(date).getFullYear()
		let month = new Date(date).getMonth() + 1
		let nextMonthFirthDay = new Date(year, month, 1)
		let oneDay = 1000 * 60 * 60 * 24
		let endDay = new Date(nextMonthFirthDay - oneDay)
		let result = this.getFormatDate(endDay, format)
		return result
	},

	/* 路程单位米转公里（小于1公里显示米，小于10公里保留一位小数，大于10公里为整数）
		 minute: 待计算米数
		 type: 1.单位-米、公里，2.单位-m、km
	*/
	meterToKilometer(meter, type = 1) {
		if (parseFloat(meter) < 1000) {
			return meter + (type == 2 ? "m" : "米")
		} else if (parseFloat(meter) < 10000) {
			let result = parseFloat(parseFloat(meter) / 1000).toFixed(1)
			return result + (type == 2 ? "km" : "公里")
		} else {
			let result = parseInt(parseFloat(meter) / 1000)
			return result + (type == 2 ? "km" : "公里")
		}
	},

	// 时间单位分钟转小时（小于1小时显示分钟，大于1小时显示小时+分钟）
	minuteToHour(minute) {
		if (parseInt(minute) < 60) {
			return minute + "分钟"
		} else {
			let newHour = parseInt(parseInt(minute) / 60)
			let newMinute = parseInt(minute) % 60
			return `${newHour}小时${newMinute}分钟`
		}
	},

	// 时间单位小时转天数（小于48小时显示小时，大于48小时显示天数+小时）
	hourToDay(hour) {
		if (isNaN(hour) || parseInt(hour) <= 0) {
			return 0
		} else if (parseInt(hour) <= 48) {
			return hour + "小时"
		} else {
			let newDay = parseInt(parseInt(hour) / 24)
			let newHour = parseInt(hour) % 24
			return `${newDay}天${newHour}小时`
		}
	},

	// 查看文件
	openDocument(fileLink) {
		return new Promise((resolve, reject) => {
			// 判断有无网络
			uni.getNetworkType({
				success: (res) => {
					if (res.networkType === "none") {
						uni.showToast({
							icon: "none",
							title: "请先连接网络后操作"
						})
						uni.hideLoading()
					} else {
						uni.downloadFile({
							url: fileLink,
							success: (result) => {
								if (result.statusCode === 200) {
									uni.openDocument({
										filePath: result.tempFilePath,
										showMenu: true,
										success: () => {
											resolve()
										},
										fail: (err) => {
											reject(err)
										},
									})
								}
							},
							fail: (err) => {
								reject(err)
							}
						})
					}
				}
			})
		})
	},

	// 检查定位权限
	checkLocationPermission() {
		return new Promise(async (resolve, reject) => {
			// #ifdef MP-WEIXIN
			uni.getSetting({
				success: (setting) => {
					if (setting.authSetting && setting.authSetting.hasOwnProperty('scope.userLocation')) {
						if (setting.authSetting['scope.userLocation']) {
							resolve(1);
						} else {
							resolve(2);
						}
					} else {
						resolve(1);
					}
				},
				fail: () => {
					reject(new Error('位置获取失败'));
				},
			})
			// #endif
			// #ifdef APP
			// resolve：1.已打开定位权限，2.无定位权限，3.未打开系统定位
			try {
				const systemLocation = permission.checkSystemEnableLocation()
				if (systemLocation) {
					var result = ""
					if (plus.os.name == "iOS") {
						result = permission.judgeIosPermissionLocation() ? 1 : 2
					} else {
						result = await permission.requestAndroidPermission("android.permission.ACCESS_FINE_LOCATION")
					}
					if (result == 1) resolve(1)
					else resolve(2)
				} else resolve(3)
			} catch (error) {
				reject(new Error('位置获取失败'));
			}
			// #endif
		})
	},

	// 设置定位权限 status：2.APP定位权限，3.系统定位服务
	setLocationPermission(status, fn) {
		// #ifdef MP-WEIXIN
		uni.showModal({
			title: "提示",
			content: "请重新授权获取您的地理位置，否则部分功能将无法使用",
			confirmText: "授权",
			success: (res) => {
				if (res.confirm) {
					uni.openSetting({
						success: () => {
							fn(true)
						},
						fail: () => {
							fn(false)
							uni.showToast({
								title: '位置获取失败',
								icon: 'none',
								duration: 2000,
							})
						},
					})
				} else {
					fn(false)
					uni.showToast({
						title: '请授权获取您的地理位置，否则部分功能将无法使用',
						icon: 'none',
						duration: 2000,
					})
				}
			}
		})
		// #endif
		// #ifdef APP
		uni.showModal({
			title: status == 3 ? '打开定位服务' : '打开定位权限',
			content: status == 3 ? '为了提供精准的定位服务，请在系统设置中打开定位服务' : '为了提供精准的定位服务，请在系统设置中开启位置信息权限',
			confirmText: '设置',
			success: (res) => {
				if (res.confirm) {
					permission.gotoAppPermissionSetting(status == 3 ? 2 : 1)
					fn(true)
				} else {
					fn(false)
					uni.showToast({
						title: '请授权获取您的地理位置，否则部分功能将无法使用',
						icon: 'none',
						duration: 2000,
					})
				}
			},
		})
		// #endif
	},
}